
// #include "test.h"
#include "netlib/net/socket/acceptor.h"

#include "netlib/net/event/event_loop.h"
#include "netlib/net/socket/socket_ops.h"

netlib::net::Acceptor::Acceptor(EventLoop* loop, const InetAddress& addr) :
    loop_(loop), accept_sock_(addr), accept_channel_(loop, accept_sock_.Fd()) {
	// sockets::bindOrDie(accept_sock_.fd(), addr.sockaddr());
	accept_sock_.Bind(addr.GetSockaddr());
	// accept_channel_.SetReadCallback(std::bind(&Acceptor::HandleRead, this));
	accept_channel_.SetReadCallback([&](Timestamp) { HandleRead(); });
}

netlib::net::Acceptor::~Acceptor() {
	accept_channel_.DisableAll();
	accept_channel_.Remove();
}

void netlib::net::Acceptor::Listen() {
	loop_->AssertInLoopThread();
	is_listening_ = true;
	accept_sock_.Listen();
	accept_channel_.EnableReading();
}

void netlib::net::Acceptor::HandleRead() {
	loop_->AssertInLoopThread();
	InetAddress peer_addr;
	int connfd = accept_sock_.Accept(&peer_addr);
	if (connfd >= 0) {
		if (callback_) {
			callback_(connfd, peer_addr);
		} else {
			close(connfd);
		}
	}
}
